#include "DragWindowArea.h"

#include "Widgets/Window.h"
#include "Widgets/WidgetTree.h"

void RMouseDragWindowArea::FirstTimeInitializeObject()
{
    Super::FirstTimeInitializeObject();

    Drag->bIsEnabled=true;
    
    Drag->Direction=EDragDirection::Customized;

    Drag->OnDragStarted.Bind([this](){
        MousePositionOnDragStarted= SMouseButtonEvent::GetMosuePositionOnScreen();
        RWindowPtr Window= GetWidgetTree()->GetWindow();
        Window->StartCaptureMouse();

        WindowPositionOnDragStarted=Window->GetWindowPosition();

        if(Window->IsMaximized())
        {   
            auto WindowWidth=Window->GetWindowSize().X;

            float MouseHorizontalPercent=MousePositionOnDragStarted.X/(float)WindowWidth; 

            Window->Restore();

            auto NewWindowWidth=Window->GetWindowSize().X;
            int32_t MouseRelativeX=NewWindowWidth*MouseHorizontalPercent;

            WindowPositionOnDragStarted.X=MousePositionOnDragStarted.X-MouseRelativeX;

            Window->SetWindowPosition(WindowPositionOnDragStarted);
        }


    });
    Drag->OnDragMoved.Bind([this](const SVec2&){
        auto MousePosition=SMouseButtonEvent::GetMosuePositionOnScreen();
        auto Delta=MousePosition-MousePositionOnDragStarted;
        auto NewWindowPosition=WindowPositionOnDragStarted + Delta;
        RWindowPtr Window= GetWidgetTree()->GetWindow();        
        Window->SetWindowPosition(NewWindowPosition);
    });

    Drag->OnDragEnded.Bind([this](){
        RWindowPtr Window= GetWidgetTree()->GetWindow();
        Window->StopCaptureMouse();
    });

    OnDoubleClicked.BindLambda([this](const SMouseButtonEvent& InMouseEvent){
        RWindowPtr Window= GetWidgetTree()->GetWindow(); 
        if(Window->IsMaximized())
        {
            Window->Restore();  
        } 
        else
        {
            Window->Maximize();
        } 
        return true;
    });
}